<?php

namespace service;

use Yii;

/**
 * Class BaseService
 * 服务层基类，单例调用
 * @package common
 */
class BaseService
{
    /**
     * 从容器中获取单实例
     *
     * @return static
     */
    public static function instance()
    {
        $container = Yii::$container;
        if (!$container->hasSingleton(static::class)) {
            $container->setSingleton(static::class);
        }
        return $container->get(static::class);
    }

    /**
     * @param int $code
     * @param mixed $data
     * @param string $info
     * @return array
     */
    protected function retArray($code, $data = null, $info = '')
    {
        return ['code' => (int)$code, 'data' => $data, 'info' => $info];
    }

    /**
     * @param $code
     * @param string $info
     * @throws \yii\base\ExitException
     */
    protected function endFail($code, $info = '')
    {
        $this->endJson($code, null, $info);
    }

    /**
     * @param $code
     * @param null $data
     * @param string $info
     * @throws \yii\base\ExitException
     */
    protected function endJson($code, $data = null, $info = '')
    {
        $result = [
            'code' => $code,
            'data' => $data === null ? new \stdClass() : $data,
            'info' => $info == '' ? Yii::t('app/error', $code) : $info,
        ];
        $this->writeJson($result);
        Yii::$app->end();
    }

    /**
     * 输出json数据
     *
     * @param     $data
     * @param int $cacheTime
     *
     * @return Response
     */
    public function writeJson($data, $cacheTime = 0)
    {
        $response         = Yii::$app->getResponse();
        $response->format = 'json';
        $response->data   = $data;
        
        $headers = $response->getHeaders();
        $headers->set('x-time', date('Y-m-d H:i:s'));
        
        // CDN缓存
        if ($cacheTime > 0) {
            $headers->set("Pragma", 'public');
            $headers->set("Cache-Control", sprintf("max-age=%d, s-maxage=%d", $cacheTime, $cacheTime));
            $headers->set("Expires", gmdate("r", time() + $cacheTime) . " GMT");
        } else {
            $headers->set("Pragma", 'no-cache');
            $headers->set("Cache-Control", 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
            $headers->set("Expires", gmdate("r", 0) . " GMT");
        }
        
        return $response;
    }
}
